package com.uto.backend;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class HttpConnnectionThread implements Runnable, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2819196720512883058L;

	public static final String DATA = "data";
	
	public static final String POST = "POST";
	public static final String GET = "GET";

	private static String TAG = "UTO_HTTP";

	private HttpRequestBuilder listener;

	private String url;

	private JSONObject data;
	
	private String method;

	public HttpConnnectionThread(HttpRequestBuilder listener, String method,
			String url, JSONObject data) {
		this.listener = listener;
		this.url = url;
		this.method = method;
		this.data = data;
	}

	public void postData() {

		// Create a new HttpClient and Post Header
		DefaultHttpClient httpclient = new DefaultHttpClient();
		Log.v(TAG, "url is: "+url);

		HttpRequestBase httpRequest = null;
		if (method==POST){
			HttpPost httpPost = new HttpPost(url);
			if (data!=null){
				try {
					httpPost.setEntity(new StringEntity(data.toString()));
				} catch (UnsupportedEncodingException e) {
					Log.v(TAG, e.toString());
					e.printStackTrace();
					listener.handleResponse(null);
				}
			}
			httpRequest = httpPost;
		}
		else if (method==GET)
		{
			httpRequest = new HttpGet(url);
			
		}
		
		try{
			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httpRequest);

			Log.v(TAG, "request execution was succsefull");
			listener.handleResponse(response);
		} catch (Exception e) {
			Log.v(TAG, e.toString());
			listener.handleResponse(null);
		}
	}

	public void run() {
		postData();
	}

}
